package civicinity.ist.psu.edu.share;

import java.util.ArrayList;

import civicinity.ist.psu.edu.R;
import civicinity.ist.psu.edu.constants.Constants;
import civicinity.ist.psu.edu.databases.CivicinityDatabase;
import civicinity.ist.psu.edu.utils.CivicinityCameraMode;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;

public class CivicinityShareMapview extends MapActivity implements LocationListener, OnItemClickListener{

	// Map related variables
	private LocationManager mLocManager = null;
	private MapView mMapView = null;
	private MyLocationOverlay mMyOverLay = null;
	private MapController mMapController = null;
	private ImageView changeViewBtn;
	private ImageView cameraBtn;
	
	private double mLatitude 		= 34.06946321;
	private double mLongitude 		= -118.44296421;
	
	private Drawable mMarker;
	
	private CivicinityDatabase mDB;
	
	private ArrayList<ShareItem> mArr;
	
	private boolean mFirstGPS = false;
	private boolean mSatelliteView = false;
	
	private static final int SELECT_PICTURE = 1;
	private String mSelectedImagePath;
	private SharedPreferences mPref;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.share_map_view);

	    mDB = new CivicinityDatabase(this);
	    mArr = new ArrayList<ShareItem>();
	    mPref = PreferenceManager.getDefaultSharedPreferences(this);
	    
	    changeViewBtn = (ImageView) findViewById(R.id.view_change);
	    cameraBtn = (ImageView) findViewById(R.id.camera_mode);
	    
	    // Set MapView and the longPressListener
		mMapView = (MapView)findViewById(R.id.map);
		mMapView.setBuiltInZoomControls(true);
		mMapView.setSatellite(false);
	    
		// Add mylocation overlay
		mMyOverLay = new MyLocationOverlay(this, mMapView);
		mMyOverLay.enableMyLocation();
		mMyOverLay.enableCompass();
		
		// get map controller
		mMapController = mMapView.getController();
		mMapController.setZoom(13);

		// initialize marker
		mMarker = getResources().getDrawable(R.drawable.marker);
		mMarker.setBounds(0, 0, mMarker.getIntrinsicWidth(), mMarker.getIntrinsicHeight());
		
		// initialize LocationManager
		mLocManager = (LocationManager)getSystemService(LOCATION_SERVICE);
		
		changeViewBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				//startActivity(new Intent(CivicinityShareListview.this, CivicinityMainpage.class));
				startActivity(new Intent(CivicinityShareMapview.this, CivicinityShareListview.class));
				finish();
			}
		});
	    
	    cameraBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				
				if(mPref.getBoolean("guest_mode", false)) {
					new AlertDialog.Builder(CivicinityShareMapview.this)
			   		.setTitle("Upload photo")
			   		.setMessage("Make sure you are able to take a photo and save it into the SD card, but cannot upload a photo to the server since you logged in as 'GUEST'")
			   		.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
						
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							openDialog();
						}
					})
			   		.show();
				}
				else {
					openDialog();
				}
			}
		});
		
	    // TODO Auto-generated method stub
	}
	
	public void openDialog() {
		final CharSequence[] choiceSeq = {"Choose from Gallery", "Capture a photo"};
		
		new AlertDialog.Builder(CivicinityShareMapview.this)
   		.setTitle("Upload photo")
   		.setItems(choiceSeq, new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				if(which == 0) {
					Intent intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
				}
				else {
					Intent intent = new Intent(CivicinityShareMapview.this, CivicinityCameraMode.class);
					intent.putExtra("prev_activity", Constants.PREV_ACITIVITY_SHARE);
					startActivity(intent);
				}
			}
		})
   		.show();
	}
	
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            mSelectedImagePath = getPath(selectedImageUri);
	            
	            Intent intent = new Intent(this, CivicinityMyView.class);
	            intent.putExtra("image_path", mSelectedImagePath);
	            startActivity(intent);
	            
	            finish();
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}
	
	/* Request updates at startup */
	@Override
	protected void onResume() {
		super.onResume();
		// get information for displaying the markers.
		getMarkerLists();
		
		// set-up the location updates.	
		mLocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 20000, 1, this);
	}

	/* Remove the locationlistener updates when Activity is paused */
	@Override
	protected void onPause() {
		super.onPause();
		mLocManager.removeUpdates(this);
	}
	
	public void onDestroy() {
		super.onDestroy();
		mLocManager.removeUpdates(this);
		
		mMyOverLay.disableCompass();
		mMyOverLay.disableMyLocation();
		
		SharedPreferences.Editor editor = mPref.edit();
		editor.putString("latitude", String.valueOf(mLatitude));
		editor.putString("longitude", String.valueOf(mLongitude));	        
		editor.commit();
	}
	
	private void getMarkerLists() {
		
		mArr = mDB.getShareOthers(0);

		setMapComponents();
	}
	
	
	private void setMapComponents() {
		
		mMapView.getOverlays().clear();
		mMapView.invalidate();
		
		mMapView.getOverlays().add(new CivicinityMapOverlay(mMapView, mMarker, mArr));
		mMapView.getOverlays().add(mMyOverLay);
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		if(location != null) {
			// calculate distance from mylocation to the marker
			
			mLatitude = location.getLatitude() * 1E6;
			mLongitude = location.getLongitude() * 1E6;
			GeoPoint point = new GeoPoint((int)mLatitude, (int)mLongitude);
			
			if(!mFirstGPS) {
				mMapController.animateTo(point);
				mFirstGPS = true;
			}
		}
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		super.onCreateOptionsMenu(menu);
		
		menu.add(0, 1, 0, getString(R.string.my_location)).setIcon(android.R.drawable.ic_menu_mylocation);
		menu.add(0, 2, 0, getString(R.string.satellite_view)).setIcon(android.R.drawable.ic_menu_mapmode);
		
		return true;
	}
	
	//Menu option selection handling
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
			case 1:
				if(mLatitude != 0.0 && mLongitude != 0.0) {
					GeoPoint point = new GeoPoint((int)mLatitude, (int)mLongitude);
					mMapController.animateTo(point);
				}
				else {
					
				}
				return true;		
			case 2:
				if(mSatelliteView) {
					mMapView.setSatellite(false);
					mSatelliteView = false;
				}
				else {
					mMapView.setSatellite(true);
					mSatelliteView = true;
				}
				return true;
		}
		return false;
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
	}
}
